package com.zygh.lz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zygh.lz.constant.SystemCon;
import com.zygh.lz.dao.*;
import com.zygh.lz.dao.role.SysRoleMapper;
import com.zygh.lz.dao.role.SysUserRoleMapper;
import com.zygh.lz.entity.Section;
import com.zygh.lz.entity.Sign;
import com.zygh.lz.entity.Staff;
import com.zygh.lz.entity.Xarea;
import com.zygh.lz.entity.role.SysRole;
import com.zygh.lz.entity.role.SysUserRole;
import com.zygh.lz.entity.vo.JobInfoVo;
import com.zygh.lz.service.SectionService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.vo.ResultBean;
import com.zygh.lz.vo.ResultBeans;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SectionServiceImpl extends ServiceImpl<SectionMapper, Section> implements SectionService {
    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private StaffMapper staffMapper;
    @Resource
    private XareaMapper xareaMapper;
    @Resource
    private SignMapper signMapper;
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private DutyModelMapper dutyModelMapper;

    /**
     * 新增人员
     *
     * @param section
     * @return
     */
    @Override
    public ResultBean addSection(Section section) {
        return ResultUtil.execOp(sectionMapper.insertSelective(section), "添加");
    }

    /**
     * 根据id修改部门
     *
     * @param section
     * @return
     */
    @Override
    public ResultBean modefiSectionById(Section section) {
        return ResultUtil.execOp(sectionMapper.updateByPrimaryKeySelective(section), "修改");
    }

    /**
     * 根据id删除部门
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean delSectionById(Integer id) {
        int num = sectionMapper.selectByPid(id);
        int count = staffMapper.selectBySectionId(id);
        if (num > 0 || count > 0) {
            return ResultUtil.setError(SystemCon.RERROR1, "该部门下有子部门，不能删除！", null);
        }
        return ResultUtil.execOp(sectionMapper.deleteByPrimaryKey(id), "删除");
    }


    @Override
    public ResultBean selectSectionByPid() {
        List<Section> sections = sectionMapper.selectList(null);
        sections = sections.stream().filter(section -> !section.getSectionName().equals("八支队")).collect(Collectors.toList());
        return ResultUtil.setOK("success", buildTreeDepts(sections));
    }


    /**
     * 按层级推送
     *
     * @return
     */
    @Override
    public ResultBean selectAllSection(String sectionname) {
        List<Section> sections = sectionMapper.selectAllSection(sectionname);
        List<Section> sectionList = new ArrayList<Section>();
        for (int i = 0; i < sections.size(); i++) {
            // 一级菜单没有parentId
            if (sections.get(i).getSectionPid() == 0) {
                sectionList.add(sections.get(i));
            }
        }
        Iterator iterList = sectionList.iterator();
        while (iterList.hasNext()) {
            Section treemenu = (Section) iterList.next();
            treemenu.setSectionList(getChild(treemenu.getSysSectionId(), sections));
        }

        return ResultUtil.setOK("success", sectionList);
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public ResultBean selectAllSectionInfo(String sectionname) {
        List<Section> sections = sectionMapper.selectAllSection(sectionname);
        if (sections.size() > 0) {
            return ResultUtil.setOK("success", sections);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 部门人员信息查询那里的模糊查询
     */
    @Override
    public ResultBean selectSectionByCt(String sex, String staffHierarchy, String sectionName) {
        List<Section> sections = sectionMapper.selectSectionByCt(sex, staffHierarchy, sectionName);
        if (sections.size() > 0) {
            return ResultUtil.setOK("success", sections);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * @param sectionId
     * @return
     */
    @Override
    public ResultBean selectBySectionId(Integer sectionId, String staffHierarchy) {
        List<Object> list = sectionMapper.selectBySectionId(sectionId, staffHierarchy);
        if (list.size() > 0) {
            return ResultUtil.setOK("success", list);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    /**
     * 根据大队id查询大队下面的中队
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean selectDetachmentByid(Integer id) {
        List<Section> sections = sectionMapper.selectDetachmentByid(id);
        if (sections.size() > 0) {
            return ResultUtil.setOK("success", sections);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    private List<Section> getChild(int id, List<Section> sections) {//int id  id 是指当前菜单id，rootMenu是指要查找的列表
        List<Section> childList = new ArrayList<>();
        Iterator iterList = sections.iterator();
        while (iterList.hasNext()) {
            Section treemenu = (Section) iterList.next();
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (treemenu.getSectionPid() != 0) {
                if (treemenu.getSectionPid() == id) {
                    childList.add(treemenu);
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        /*for (Treemenu treemenu : childList) {*/
        Iterator iterList2 = childList.iterator();
        while (iterList2.hasNext()) {
            Section treemenu = (Section) iterList2.next();
            treemenu.setSectionList(getChild(treemenu.getSysSectionId(), sections));
        } // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    //部门层级列表
    @Override
    public ResultBean findSectionByTier(String sectionname) {
        List<Section> sections = sectionMapper.selectAllSection(sectionname);
        //父级菜单集合
        List<Section> sectionList = new ArrayList<Section>();
        //子集菜单集合
        List<Section> selectBySublevel = new ArrayList<Section>();
        //三级菜单集合
        List<Section> levelMenu = new ArrayList<Section>();
        //父级菜单
        for (int i = 0; i < sections.size(); i++) {
            if (sections.get(i).getSectionPid() == 0) {
                sectionList.add(sections.get(i));
            }
        }
        //子级大队菜单
        Iterator iterList = sectionList.iterator();
        while (iterList.hasNext()) {
            Section treemenu = (Section) iterList.next();
            selectBySublevel = sectionMapper.findSelectBySublevel(treemenu.getSysSectionId(), 0);
            treemenu.setSectionList(selectBySublevel);
        }
        //三级菜单集合
        Iterator<Section> iterator = selectBySublevel.iterator();
        while (iterator.hasNext()) {
            Section next = iterator.next();
            levelMenu = xareaMapper.findLevelMenu(next.getSysSectionId());
            next.setSectionList(levelMenu);
        }
        return ResultUtil.setOK("success", sectionList);
    }

    //日常勤务列表
    @Override
    public ResultBeans findSectionById(Integer sectionId, String policeNumber) {
        Sign sign = signMapper.findSignIn(policeNumber, "1");
        List<Map<String, Object>> stationByXarea = xareaMapper.findStationByXarea(sectionId);
        for (Map<String, Object> map : stationByXarea) {
            List<Map<String, Object>> callsign = xareaMapper.findStationDetail(sectionId, map.get("callsign").toString());
            for (Map<String, Object> map1 : callsign) {
                if (sign != null) {
                    if (Integer.valueOf(map1.get("id").toString()) == (sign.getAssignmentid())) {
                        map1.put("signState", 1);
                    } else {
                        map1.put("signState", 0);
                    }
                } else {
                    map1.put("signState", 0);
                }
            }
            map.put("detachment", callsign);
        }
        return ResultUtil.resultBeansSuccess(stationByXarea);

    }

    /**
     * 漏签统计大队展示
     *
     * @param id
     * @return
     */
    @Override
    public ResultBean findSectionByid(Integer id) {
        List<Section> sectionByid = sectionMapper.findSectionByid(id);
        if (sectionByid != null) {
            return ResultUtil.setOK("success", sectionByid);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }

    @Override
    public ResultBean findSectionTier(Integer id) {
        List<Section> sectionByid = sectionMapper.findSectionByid(id);
        for (Section section : sectionByid) {
            List<Section> sectionByLochus = sectionMapper.findSectionByLochus(section.getSysSectionId());
            section.setSectionList(sectionByLochus);
        }
        if (sectionByid != null) {
            return ResultUtil.setOK("success", sectionByid);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    @Override
    public ResultBean findSectionTiers(Integer id) {
        List<Section> sectionByid = sectionMapper.findSectionByid(id);
        sectionByid = sectionByid.stream().filter(section -> !section.getSectionName().equals("八支队")).collect(Collectors.toList());
        for (Section section : sectionByid) {
            List<Section> sectionByLochus = sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                    .eq(Section::getSectionPid, section.getSysSectionId()));
            section.setSectionList(sectionByLochus);
        }
        if (sectionByid != null) {
            return ResultUtil.setOK("success", sectionByid);
        }
        return ResultUtil.setError(SystemCon.RERROR1, "error", null);
    }


    @Override
    public ResultBean getSectionTree(Integer id) {
        List<Section> sections = sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                .eq(id != null, Section::getSectionPid, id)
                .or().eq(id != null, Section::getSysSectionId, id)
                .orderByAsc(Section::getSort));
        if (id == null) {
            id = 0;
        } else {
            Section section = sectionMapper.selectByPrimaryKey(id);
            id = section.getSectionPid();
        }
        return ResultUtil.setOK("success", buildTreeDept(sections, id));
    }

    @Override
    public ResultBean updateSectionByIds(Section section) {
        return ResultUtil.setOK("success", sectionMapper.updateById(section));
    }

    @Override
    public List<Integer> findSectionNum(Integer id) {

        return sectionMapper.findSectionNum(id);
    }

    @Override
    public List<Map<String, Object>> findSectionsByPid(Integer pid) {
        List<Map<String, Object>> sectionsByPid = sectionMapper.findSectionsByPid(pid);
        for (Map<String, Object> map : sectionsByPid) {
            map.put("onLineNum", signMapper.OnlineStaff(map.get("id").toString()).size());
        }
        return sectionsByPid;
    }

    @Override
    public ResultBean getSectionRoleTree(Integer id) {
        Section sections = sectionMapper.selectOne(Wrappers.<Section>lambdaQuery()
                .eq(Section::getSectionPid, 0)
                .orderByAsc(Section::getSort));
        List<Section> sections1 = sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                .eq(Section::getSectionPid, sections.getSysSectionId()));
        sections1.add(0, sections);
        for (Section section : sections1) {
            List<SysRole> role = sysRoleMapper.getRole(section.getSysSectionId());
            section.setRole(role);
        }

        return ResultUtil.setOK("查询成功", sections1);
    }

    @Override
    public ResultBean man(Integer sysSectionId, Integer id, Integer page, Integer num) {
        PageHelper.startPage(page, num);
        List<Map> data = sysRoleMapper.selectRole(sysSectionId, id);
        PageInfo<Map> da = new PageInfo<>(data);
        return ResultUtil.setOK("查询成功", da);
    }

    @Override
    @Transactional
    public ResultBean updateMan(Staff staff) {
        staffMapper.updateById(staff);
        sysUserRoleMapper.delete(Wrappers.<SysUserRole>lambdaQuery()
                .eq(SysUserRole::getUserId, staff.getSysStaffId()));
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(Long.valueOf(staff.getSysStaffId()));
        sysUserRole.setRoleId(staff.getRoleId());
        sysUserRoleMapper.insert(sysUserRole);
        return ResultUtil.setOK("操作成功", null);
    }

    @Override
    public ResultBean delete(List<Integer> staff) {

        staffMapper.delete(Wrappers.<Staff>lambdaQuery().in(Staff::getSysStaffId, staff));
        return ResultUtil.setOK("操作成功", null);
    }

    @Override
    public ResultBean getSectionAll(Integer id) {
        List<Section> sectionList = sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                .eq(Section::getSectionPid, 0)
        );
        for (Section section : sectionList) {
            section.setSectionList(sectionMapper.selectList(Wrappers.<Section>lambdaQuery()
                    //去掉八支队
                    .eq(Section::getSectionPid, section.getSysSectionId())
                    .ne(Section::getSysSectionId, 200)
                    .orderByAsc(Section::getSort)
            ));
        }
        return ResultUtil.setOK("操作成功", sectionList);
    }

    /**
     * 岗位部署，日常勤务，根据岗位类型、单位、岗位名称搜索详情
     *
     * @param postCode   岗位类型
     * @param sectionIds 单位数组
     * @param gridding   岗位名称
     * @return
     */
    @Override
    public ResultBean findByCondition(Integer postCode, int[] sectionIds, String gridding) {
        Map<String, Object> map = new HashMap<>();
        List<Xarea> xareaList = xareaMapper.findByCondition(postCode, sectionIds, gridding);
        List<Map<String, Object>> detailMapList = new ArrayList<>(); //全部详情信息
        //大队名称集合
        List<String> battalionList = new ArrayList<>();
        List<String> postList = xareaList.stream().map(Xarea::getGridding).distinct().collect(Collectors.toList()); //过滤去重
        Integer sumPolice = 0;
        Integer sumAuxiliary = 0;
        for (Xarea xarea : xareaList) {
            if (xarea.getPolice() != null) {
                sumPolice += xarea.getPolice();
            }
            if (xarea.getAuxiliary() != null) {
                sumAuxiliary += xarea.getAuxiliary();
            }
            if (xarea.getStation() != null && xarea.getBattalion() != null) {
                //stationSet.add(xarea.getStation());  //岗位类型
                battalionList.add(xarea.getBattalion()); //大队名称
            }
        }
        battalionList = battalionList.stream().distinct().collect(Collectors.toList()); //过滤去重
        for (String battalion : battalionList) {
            Map<String, Object> detailMap = new HashMap<>();
            detailMap.put("section", battalion);  //大队名称
            List<Map<String, Object>> xareas = new ArrayList<>(); //岗位详情集合
            for (Xarea xarea : xareaList) {
                Map<String, Object> map2 = new HashMap<>();  //岗位详情
                if (xarea.getBattalion() != null && xarea.getBattalion().equals(battalion)) {
                    if (xarea.getGridding() != null && xarea.getDetachment() != null && !xarea.getGridding().contains("大队") && !xarea.getGridding().contains("支队")) {
                        String gridd = xarea.getDetachment() + xarea.getGridding();  //岗位名称
                        map2.put("gridding", gridd);
                    } else {
                        map2.put("gridding", xarea.getGridding());
                    }
                    String patternName = dutyModelMapper.getByCode(xarea.getPattern()); //勤务模式
                    map2.put("id", xarea.getId());
                    map2.put("name", xarea.getName());
                    map2.put("station", xarea.getStation());
                    map2.put("sectionZid", xarea.getSectionZid());
                    map2.put("sectionDid", xarea.getSectionDid());
                    map2.put("police", xarea.getPolice());
                    map2.put("auxiliary", xarea.getAuxiliary());
                    map2.put("patternName", patternName);

                    xareas.add(map2);
                }
            }
            detailMap.put("posts", xareas);
            detailMapList.add(detailMap);

        }
        Map<String, Object> countMap = new HashMap<>();
        //岗位数量
        countMap.put("postCount", postList.size());
        //民警数量
        countMap.put("sumPolice", sumPolice);
        //辅警数量
        countMap.put("sumAuxiliary", sumAuxiliary);

        //岗位详情
        map.put("detailList", detailMapList);
        //数量
        map.put("count", countMap);
        return ResultUtil.setOK("操作成功", map);
    }

    /**
     * 根据岗位id查询签到人员详细信息，民警，辅警
     */
    @Override
    public ResultBean getByPostId(Integer id) {
        Map<String, Object> map = new HashMap<>();
        List<JobInfoVo> jobInfoVos = xareaMapper.getByPostId(id);

//        log.info(JSON.toJSONString(jobInfoVos));
        //民警
        List<String> sumPolice = new ArrayList<>();
        //辅警
        List<String> sumAuxiliary = new ArrayList<>();
        for (JobInfoVo infoVo : jobInfoVos) {
            if (ObjectUtil.isNotEmpty(infoVo.getStafftype()) && infoVo.getStafftype().equals("民警")) {
                sumPolice.add(infoVo.getWarningsignal());
            }
            if (ObjectUtil.isNotEmpty(infoVo.getStafftype()) && infoVo.getStafftype().equals("辅警")) {
                sumAuxiliary.add(infoVo.getWarningsignal());
            }
        }

        Map<String, Object> countMap = new HashMap<>();
        //民警数量
        countMap.put("sumPolice", sumPolice.size());
        //辅警数量
        countMap.put("sumAuxiliary", sumAuxiliary.size());

        //在线警力信息
        map.put("policeMsg", jobInfoVos);
        //在线警力数量
        map.put("count", countMap);
        return ResultUtil.setOK("操作成功", map);
    }


    private List<Section> buildTreeDept(List<Section> list, int id) {
        List<Section> deptList = new ArrayList<>();

        for (Section sysDept : list) {
            for (Section dept : list) {
                if (sysDept.getSysSectionId().equals(dept.getSectionPid())) {
                    String name = dept.getSectionName();
//                    if (!name.equals("八支队") && !name.equals("辅警办") && !name.equals("监察室（纪委）") && !name.equals("考核办") && !name.equals("交通肇事逃逸案件侦查支队") && !name.equals("交通指挥中心") && !name.equals("警务综合处")) {
//                        sysDept.getSectionList().add(dept);
//                    }
                    sysDept.getSectionList().add(dept);
                }
            }

            //提取父级节点
            if (sysDept.getSectionPid() == id) {
                deptList.add(sysDept);
            }

        }
        return deptList;

    }

    private List<Section> buildTreeDepts(List<Section> list) {
        List<Section> deptList = new ArrayList<>();

        for (Section sysDept : list) {
            for (Section dept : list) {
                if (sysDept.getSysSectionId().equals(dept.getSectionPid())) {
                    sysDept.getSectionList().add(dept);
                }
            }

            //提取父级节点
            if (sysDept.getSectionPid() == 74) {
                deptList.add(sysDept);
            }

        }
        return deptList;

    }

}
